﻿using MaterialManagement.API.Application.Command.ERP;
using MaterialManagement.Domain.ERP;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Interface;
using MediatR;

namespace MaterialManagement.API.Application.Handler.ERP
{
    public class GetPinkingOrderHandler : IRequestHandler<GetPinkingOrderCommand, APIPaging<OutboundRecordModel>>
    {
        private readonly IBaseRepository<OutboundRecordModel> outboundRecordRepo;
        private readonly IBaseRepository<PickingModel> pickingRepo;

        public GetPinkingOrderHandler(IBaseRepository<OutboundRecordModel> outboundRecordRepo,
                                        IBaseRepository<PickingModel> pickingRepo)
        {
            this.outboundRecordRepo = outboundRecordRepo;
            this.pickingRepo = pickingRepo;
        }
        public Task<APIPaging<OutboundRecordModel>> Handle(GetPinkingOrderCommand request, CancellationToken cancellationToken)
        {
            APIPaging<OutboundRecordModel> result = new APIPaging<OutboundRecordModel>();
            var res = outboundRecordRepo.GetAll().Where(x => !x.IsDel);
            if (!string.IsNullOrEmpty(request.PickFormCode))
            {
                res = res.Where(x => x.PickFormCode.Contains(request.PickFormCode));
            }
            if (!string.IsNullOrEmpty(request.Production))
            {
                res = res.Where(x => x.ProductionOrdersCode.Contains(request.Production));
            }
            var query = res.ToList();
            foreach (var order in query)
            {
                order.PickInfo = pickingRepo.GetAll().Where(x => x.PickFormCode == order.PickFormCode).Count();
                order.PickTotal = pickingRepo.GetAll().Where(x => x.PickFormCode == order.PickFormCode).Select(x => x.PickingQuantity).Sum();
            }
            result.TotalCount = query.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            result.PageDatas = query.OrderByDescending(x => x.PickDate).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            return Task.FromResult(result);
        }
    }
}
